import request from '@/utils/request'

// 权限类型定义
export interface Permission {
  id: number
  name: string
  code: string
  description: string
  pid?: number
  children?: Permission[]
  level: number
  isLeaf: boolean
  status: string
  createdAt: string
  updatedAt: string
}

// 角色类型定义
export interface Role {
  id: string
  name: string
  description: string
  permissions: string[]
  createdAt: string
  updatedAt: string
}

// 角色查询参数
export interface RoleQuery {
  page?: number
  pageSize?: number
  keyword?: string
}

// 创建角色
export const createRole = (roleData: Omit<Role, 'id' | 'createdAt' | 'updatedAt'>) => {
  return request.post<Role>('/roles', roleData)
}

// 获取角色列表
export const getRoles = (query?: RoleQuery) => {
  return request.get<{ list: Role[]; total: number }>('/roles', { params: query }) as unknown as Promise<{ list: Role[]; total: number }>
}



// 获取单个角色
export const getRole = (id: string) => {
  return request.get<Role>(`/roles/${id}`)
}

// 更新角色
export const updateRole = (
  id: string,
  roleData: Partial<Omit<Role, 'id' | 'createdAt' | 'updatedAt'>>,
) => {
  return request.put<Role>(`/roles/${id}`, roleData)
}

// 删除角色
export const deleteRole = (id: string) => {
  return request.delete(`/roles/${id}`)
}

// 批量删除角色
export const batchDeleteRoles = (ids: string[]) => {
  return request.delete('/roles/batch', { data: { ids } })
}

// 获取权限列表
export const getPermissions = () => {
  return request.get<Permission[]>('/permissions') as unknown as Promise<Permission[]>
}

// 分配角色权限
export const assignPermissions = (roleId: string, permissionIds: string[]) => {
  return request.post(`/roles/${roleId}/permissions`, { permissionIds })
}

// 获取角色权限
export const getRolePermissions = (roleId: string) => {
  return request.get<string[]>(`/roles/${roleId}/permissions`) as unknown as Promise<string[]>
}

// 创建权限
export const createPermission = (
  permissionData: Omit<Permission, 'id' | 'children' | 'createdAt' | 'updatedAt'>,
) => {
  return request.post<Permission>('/permissions', permissionData)
}

// 更新权限
export const updatePermission = (
  id: number,
  permissionData: Partial<Omit<Permission, 'id' | 'children' | 'createdAt' | 'updatedAt'>>,
) => {
  return request.put<Permission>(`/permissions/${id}`, permissionData)
}

// 删除权限
export const deletePermission = (id: number) => {
  return request.delete(`/permissions/${id}`) as unknown as Promise<void>
}

// 批量删除权限
export const batchDeletePermissions = (ids: number[]) => {
  return request.delete('/permissions/batch', { data: { ids } }) as unknown as Promise<void>
}
